package com.ssfeng.youxia.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssfeng.youxia.entity.Sessions;
import com.ssfeng.youxia.mapper.SessionsMapper;
import com.ssfeng.youxia.service.ISessionsService;
import com.ssfeng.youxia.shiro.SessionUtils;
import com.ssfeng.youxia.shiro.ShiroUser;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liyuhang
 * @since 2020-04-06
 */
@Service
public class SessionsServiceImpl extends ServiceImpl<SessionsMapper, Sessions> implements ISessionsService {


    @Override
    public  List<Map<String, Object>> getOnlineUsers(){
        List<Map<String, Object>> result = new ArrayList<>();
        List<Sessions> list = this.list();
        if (!CollectionUtils.isEmpty(list)) {
            for (Sessions sessions : list) {
                String sessionStr = sessions.getSession();
                Session session = SessionUtils.base64DcodeSession(sessionStr);
                ShiroUser user = SessionUtils.getUserFromSession(session);
                if (user == null) {
                    continue;
                }

                Map<String, Object> map = new HashMap<>();
                map.put("userId", user.getUserId());
                map.put("userName", user.getUserName());
                map.put("startTimestamp", session.getStartTimestamp());
                map.put("lastAccessTime", session.getLastAccessTime());
                map.put("host", session.getHost());
                map.put("sessionId", session.getId());
                result.add(map);
            }
        }
        return result;
    }


/***
 * 踢出用户
 * @param sessionId
 */

    public void kickOutUser(String sessionId) {
        Sessions sessions = baseMapper.selectById(sessionId);
        if (!StringUtils.isEmpty(sessions)) {
            String sessionStr = sessions.getSession();
            Session session = SessionUtils.base64DcodeSession(sessionStr);
            session.setAttribute(SessionUtils.SESSION_KICKOUT_KEY, true);
            sessionStr = SessionUtils.base64EncodeSession(session);
            sessions.setSession(sessionStr);
            UpdateWrapper<Sessions> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", sessions.getId());
            baseMapper.update(sessions,updateWrapper);
        }
    }

    @Override
    public int deleteExpiredSessions() {
        return 0;
    }
}
